package com.thyrsus.project.service.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thyrsus.project.dao.user.UserDAO;
import com.thyrsus.project.dao.user.entity.User;
import com.thyrsus.project.object.UserContext;
import com.thyrsus.project.object.UserObject;

@Service
public class UserService {
	
	static Logger LOGGER = Logger.getLogger(UserService.class);
	
	@Autowired
	private UserDAO userDao;
	
	public void create() {
		User usr = new User();
		usr.setMail("maximiliense@gmail.com");
		userDao.add(usr);
	}
	
	public void create(UserContext user) {
		User newUser = new User(user);
		userDao.add(newUser);
		user.setId(newUser.getId().getId());
	}
	
	public void delete() {
		LOGGER.debug("Will delete : ");
		log();
		userDao.removeAll();
	}
	
	public void log() {
		List<User> users = userDao.listUsers();
		for (int i = 0 ; i < users.size() ; i ++) {
			LOGGER.debug("User N"+(i+1)+" : "+users.get(i).getMail());
		}
		
	}
	
	public UserContext getUserContext(String mail) {
		return null;
	}
	
	public UserContext getUserContextById(Long id) {
		User user = userDao.getUser(id);
		if (user == null) {
			return null;
		} else {
			return new UserContext(user);
		}
	}
	
	public UserContext login(String mail,String password) {
		List<User> users = userDao.getUsers(mail);
		if (users.size()!=1) {
			return null;
		} else if (!users.get(0).getPassword().equals(password)) {
			return null;
		} else {
			return new UserContext(users.get(0));
		}
	}
	
	public boolean isMailExist(String mail) {
		List<User> users = userDao.getUsers(mail);
		return users.size()>0;
	}
	
	/**
	 * This function create and administrator if no administrator has already been registered
	 */
	public void createAdmin() {
		User user = new User();
		user.setFirstName("DYONISOS");
		user.setLastName("BACHUS");
		user.setIsAdmin(true);
		user.setMail("root@thyrsus.com");
		user.setPassword("whataparty");
		if (userDao.hasAdmin()) {
			LOGGER.error("createAdmin : failed...");
		} else {
			userDao.add(user);
			LOGGER.debug(" createAdmin : successful !");
		}
	}
	
	public List<UserObject> searchUsers(String searchString) {
		List<User> users = userDao.searchUsers(searchString);
		LOGGER.debug("The user search contains : "+users.size()+" results");
		List<UserObject> userObject = new ArrayList<UserObject>();
		for(User user:userDao.searchUsers(searchString)) {
			userObject.add(new UserObject(user));
		}
		return userObject;
	}

}
